package com.waterworld.watch.common.customview;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.waterworld.watch.R;

import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;

/**
 * Created by nhuan on 2019/4/1.
 */

public class MyPtrHeaderView extends FrameLayout implements PtrUIHandler {

    private TextView tvLoading;
    private ImageView spinKitView;
    private View view;
    private AnimationDrawable anim;
    public MyPtrHeaderView(Context context) {
        super(context);
        init();
    }

    public MyPtrHeaderView(@NonNull Context context,@Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyPtrHeaderView(@NonNull Context context,@Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        view = LayoutInflater.from(getContext()).inflate(R.layout.my_ptr_header,this,false);
        tvLoading = view.findViewById(R.id.tv_loading);
        spinKitView = view.findViewById(R.id.spin_kit);
        anim = (AnimationDrawable) spinKitView.getBackground();
        addView(view);
    }

    @Override
    public void onUIReset(PtrFrameLayout frame) {

    }

    @Override
    public void onUIRefreshPrepare(PtrFrameLayout frame) {

    }

    @Override
    public void onUIRefreshBegin(PtrFrameLayout frame) {
        tvLoading.setText("刷新中...");
        anim.start();
        spinKitView.setVisibility(VISIBLE);
    }

    @Override
    public void onUIRefreshComplete(PtrFrameLayout frame) {
        tvLoading.setText("刷新完成");
        anim.stop();
        spinKitView.setVisibility(GONE);
    }

    @Override
    public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
        final int mOffsetToRefresh = frame.getOffsetToRefresh();
        final int currentPos = ptrIndicator.getCurrentPosY();

        if (currentPos < mOffsetToRefresh) {
            if (status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                tvLoading.setText("下拉刷新");
            }
        } else if (currentPos > mOffsetToRefresh) {
            if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                tvLoading.setText("释放刷新");
            }
        }
    }
}
